import React, { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
import { useTranslation } from 'react-i18next'
import {
  EyeIcon,
  EyeSlashIcon,
  ShieldCheckIcon,
  UserIcon,
  LockClosedIcon,
  EnvelopeIcon,
  ExclamationTriangleIcon,
  CheckCircleIcon
} from '@heroicons/react/24/outline'
import { AppDispatch } from '@/store'
import { register as registerUser, selectAuthLoading, selectAuthError } from '@/store/slices/authSlice'
import { Card, Button, Input } from '@/components/ui'
import { ErrorBoundary } from '@/components/common'

const registerSchema = z.object({
  username: z.string()
    .min(3, 'Username must be at least 3 characters')
    .max(30, 'Username must be less than 30 characters')
    .regex(/^[a-zA-Z0-9_-]+$/, 'Username can only contain letters, numbers, hyphens, and underscores'),
  email: z.string().email('Invalid email address'),
  displayName: z.string()
    .min(2, 'Display name must be at least 2 characters')
    .max(50, 'Display name must be less than 50 characters'),
  password: z.string()
    .min(8, 'Password must be at least 8 characters')
    .regex(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)/, 'Password must contain at least one uppercase letter, one lowercase letter, and one number'),
  confirmPassword: z.string(),
  agreeToTerms: z.boolean().refine(val => val === true, 'You must agree to the terms and conditions'),
  subscribeNewsletter: z.boolean().optional()
}).refine((data) => data.password === data.confirmPassword, {
  message: "Passwords don't match",
  path: ["confirmPassword"],
})

type RegisterFormData = z.infer<typeof registerSchema>

export const RegisterPage: React.FC = () => {
  const { t } = useTranslation()
  const dispatch = useDispatch<AppDispatch>()
  const navigate = useNavigate()
  const isLoading = useSelector(selectAuthLoading)
  const error = useSelector(selectAuthError)
  const [showPassword, setShowPassword] = useState(false)
  const [showConfirmPassword, setShowConfirmPassword] = useState(false)

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch
  } = useForm<RegisterFormData>({
    resolver: zodResolver(registerSchema)
  })

  const password = watch('password')

  const onSubmit = async (data: RegisterFormData) => {
    try {
      await dispatch(registerUser({
        username: data.username,
        email: data.email,
        displayName: data.displayName,
        password: data.password,
        subscribeNewsletter: data.subscribeNewsletter
      })).unwrap()

      navigate('/auth/verify-email', {
        state: { email: data.email }
      })
    } catch (error) {
      // Error is handled by the slice
    }
  }

  // Password strength indicator
  const getPasswordStrength = (password: string) => {
    if (!password) return { strength: 0, label: '', color: '' }

    let strength = 0
    if (password.length >= 8) strength++
    if (/[a-z]/.test(password)) strength++
    if (/[A-Z]/.test(password)) strength++
    if (/\d/.test(password)) strength++
    if (/[^a-zA-Z0-9]/.test(password)) strength++

    const labels = ['Very Weak', 'Weak', 'Fair', 'Good', 'Strong']
    const colors = ['bg-red-500', 'bg-orange-500', 'bg-yellow-500', 'bg-blue-500', 'bg-green-500']

    return {
      strength,
      label: labels[strength - 1] || '',
      color: colors[strength - 1] || 'bg-gray-300'
    }
  }

  const passwordStrength = getPasswordStrength(password || '')

  return (
    <ErrorBoundary>
      <div className="min-h-screen flex">
        {/* Left Side - Branding */}
        <div className="hidden lg:flex lg:w-1/2 bg-gradient-to-br from-green-600 to-blue-700 relative overflow-hidden">
          <div className="absolute inset-0 bg-black opacity-20"></div>
          <div className="relative z-10 flex flex-col justify-center px-12 text-white">
            <div className="mb-8">
              <div className="flex items-center space-x-3 mb-6">
                <div className="p-3 bg-white bg-opacity-20 rounded-lg">
                  <ShieldCheckIcon className="h-8 w-8" />
                </div>
                <h1 className="text-3xl font-bold">Join Bai-hu Platform</h1>
              </div>
              <h2 className="text-4xl font-bold mb-4">
                {t('auth.registerTitle')}
              </h2>
              <p className="text-xl text-green-100 leading-relaxed">
                {t('auth.registerSubtitle')}
              </p>
            </div>

            <div className="space-y-4">
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-green-300" />
                <span className="text-green-100">{t('auth.features.freeAccount')}</span>
              </div>
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-green-300" />
                <span className="text-green-100">{t('auth.features.unlimitedPlugins')}</span>
              </div>
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-green-300" />
                <span className="text-green-100">{t('auth.features.analytics')}</span>
              </div>
              <div className="flex items-center space-x-3">
                <CheckCircleIcon className="w-6 h-6 text-green-300" />
                <span className="text-green-100">{t('auth.features.communitySupport')}</span>
              </div>
            </div>
          </div>
        </div>

        {/* Right Side - Registration Form */}
        <div className="flex-1 flex items-center justify-center px-4 sm:px-6 lg:px-8 bg-gray-50">
          <div className="max-w-md w-full">
            <Card className="p-8">
              <div className="text-center mb-8">
                <div className="mx-auto w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mb-4">
                  <UserIcon className="h-8 w-8 text-green-600" />
                </div>
                <h2 className="text-2xl font-bold text-gray-900">{t('auth.createAccount')}</h2>
                <p className="mt-2 text-sm text-gray-600">
                  {t('auth.alreadyHaveAccount')}{' '}
                  <Link
                    to="/auth/login"
                    className="font-medium text-primary-600 hover:text-primary-500"
                  >
                    {t('auth.signInHere')}
                  </Link>
                </p>
              </div>

              <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                {error && (
                  <div className="flex items-center p-4 bg-red-50 border border-red-200 rounded-md">
                    <ExclamationTriangleIcon className="h-5 w-5 text-red-400 mr-3" />
                    <div className="text-sm text-red-700">{error}</div>
                  </div>
                )}

                <div className="grid grid-cols-1 gap-4">
                  <Input
                    label={t('auth.username')}
                    placeholder={t('auth.enterUsername')}
                    leftIcon={<UserIcon />}
                    error={errors.username?.message}
                    {...register('username')}
                    fullWidth
                  />

                  <Input
                    label={t('auth.email')}
                    type="email"
                    placeholder={t('auth.enterEmail')}
                    leftIcon={<EnvelopeIcon />}
                    error={errors.email?.message}
                    {...register('email')}
                    fullWidth
                  />

                  <Input
                    label={t('auth.displayName')}
                    placeholder={t('auth.enterDisplayName')}
                    leftIcon={<UserIcon />}
                    error={errors.displayName?.message}
                    helperText={t('auth.displayNameHelper')}
                    {...register('displayName')}
                    fullWidth
                  />

                  <div>
                    <Input
                      label={t('auth.password')}
                      type={showPassword ? 'text' : 'password'}
                      placeholder={t('auth.createPassword')}
                      leftIcon={<LockClosedIcon />}
                      rightIcon={
                        <button
                          type="button"
                          onClick={() => setShowPassword(!showPassword)}
                          className="text-gray-400 hover:text-gray-600"
                        >
                          {showPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                        </button>
                      }
                      error={errors.password?.message}
                      {...register('password')}
                      fullWidth
                    />

                    {/* Password Strength Indicator */}
                    {password && (
                      <div className="mt-2">
                        <div className="flex items-center justify-between text-xs text-gray-600 mb-1">
                          <span>{t('auth.passwordStrength')}</span>
                          <span className={`font-medium ${
                            passwordStrength.strength >= 4 ? 'text-green-600' :
                            passwordStrength.strength >= 3 ? 'text-blue-600' :
                            passwordStrength.strength >= 2 ? 'text-yellow-600' : 'text-red-600'
                          }`}>
                            {t(`auth.passwordStrengthLevel.${passwordStrength.label.toLowerCase().replace(' ', '')}`)}
                          </span>
                        </div>
                        <div className="w-full bg-gray-200 rounded-full h-2">
                          <div
                            className={`h-2 rounded-full transition-all duration-300 ${passwordStrength.color}`}
                            style={{ width: `${(passwordStrength.strength / 5) * 100}%` }}
                          />
                        </div>
                      </div>
                    )}
                  </div>

                  <Input
                    label={t('auth.confirmPassword')}
                    type={showConfirmPassword ? 'text' : 'password'}
                    placeholder={t('auth.confirmPasswordPlaceholder')}
                    leftIcon={<LockClosedIcon />}
                    rightIcon={
                      <button
                        type="button"
                        onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                        className="text-gray-400 hover:text-gray-600"
                      >
                        {showConfirmPassword ? <EyeSlashIcon className="h-5 w-5" /> : <EyeIcon className="h-5 w-5" />}
                      </button>
                    }
                    error={errors.confirmPassword?.message}
                    {...register('confirmPassword')}
                    fullWidth
                  />
                </div>

                <div className="space-y-4">
                  <div className="flex items-start">
                    <input
                      {...register('agreeToTerms')}
                      type="checkbox"
                      className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded mt-0.5"
                    />
                    <label className="ml-3 text-sm text-gray-700">
                      {t('auth.agreeToTerms')}{' '}
                      <Link to="/terms" className="text-primary-600 hover:text-primary-500">
                        {t('auth.termsOfService')}
                      </Link>{' '}
                      {t('auth.and')}{' '}
                      <Link to="/privacy" className="text-primary-600 hover:text-primary-500">
                        {t('auth.privacyPolicy')}
                      </Link>
                    </label>
                  </div>
                  {errors.agreeToTerms && (
                    <p className="text-sm text-red-600">{errors.agreeToTerms.message}</p>
                  )}

                  <div className="flex items-start">
                    <input
                      {...register('subscribeNewsletter')}
                      type="checkbox"
                      className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded mt-0.5"
                    />
                    <label className="ml-3 text-sm text-gray-700">
                      {t('auth.subscribeNewsletter')}
                    </label>
                  </div>
                </div>

                <Button
                  type="submit"
                  loading={isLoading}
                  disabled={isLoading}
                  fullWidth
                  size="lg"
                >
                  {t('auth.createAccount')}
                </Button>

                <div className="relative">
                  <div className="absolute inset-0 flex items-center">
                    <div className="w-full border-t border-gray-300" />
                  </div>
                  <div className="relative flex justify-center text-sm">
                    <span className="px-2 bg-white text-gray-500">{t('auth.orSignUpWith')}</span>
                  </div>
                </div>

                <div className="grid grid-cols-2 gap-3">
                  <Button variant="outline" fullWidth disabled>
                    <svg className="w-5 h-5 mr-2" viewBox="0 0 24 24">
                      <path fill="currentColor" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/>
                      <path fill="currentColor" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/>
                      <path fill="currentColor" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/>
                      <path fill="currentColor" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/>
                    </svg>
                    Google
                  </Button>
                  <Button variant="outline" fullWidth disabled>
                    <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 24 24">
                      <path d="M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.024-.105-.949-.199-2.403.041-3.439.219-.937 1.219-5.160 1.219-5.160s-.312-.623-.312-1.543c0-1.446.837-2.525 1.877-2.525.885 0 1.312.663 1.312 1.456 0 .887-.565 2.211-.854 3.437-.243 1.028.515 1.866 1.527 1.866 1.833 0 3.243-1.933 3.243-4.724 0-2.471-1.777-4.197-4.316-4.197-2.94 0-4.665 2.205-4.665 4.486 0 .89.343 1.843.771 2.363.085.102.097.192.072.297-.079.327-.254 1.031-.289 1.175-.045.186-.145.225-.334.136-1.249-.581-2.03-2.407-2.03-3.874 0-3.154 2.292-6.052 6.608-6.052 3.469 0 6.165 2.473 6.165 5.776 0 3.447-2.173 6.22-5.19 6.22-1.013 0-1.966-.527-2.29-1.155l-.623 2.378c-.226.869-.835 1.958-1.244 2.621.937.29 1.931.446 2.962.446 6.624 0 11.99-5.367 11.99-11.987C24.007 5.367 18.641.001 12.017.001z"/>
                    </svg>
                    GitHub
                  </Button>
                </div>
              </form>
            </Card>
          </div>
        </div>
      </div>
    </ErrorBoundary>
  )
}
